<?php

require_once(dirname(__DIR__).'/api/DB.php');
require_once(dirname(__DIR__).'/api/response.php');
require_once(dirname(__DIR__).'/api/func.php');

$message = '';

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['email', 'password'] as $value) {

        // 判断是否有传递需要的参数
        if (!isset($_POST[$value])) {
            throw new Exception(fieldMap($value).'为必传项');
        }

        // 判断参数是否为空
        if (empty($_POST[$value])) {
            throw new Exception(fieldMap($value).'不能为空');
        }

        if ($value === 'password' && strlen($_POST[$value]) < 6) {
            throw new Exception('密码长度不能小于6位');
        }
    }

    // 判断用户密码是否正确
    $sql = 'select * from users where email = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['email']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!empty($res)) {
        if ($res['password'] !== md5($_POST['password'])) {
            throw new Exception('用户名或密码错误');
        }
    } else {
        throw new Exception('用户名或密码错误');
    };

    // 允许来自如何域的请求（开发环境使用）
    header('Access-Control-Allow-Origin: *');

    // 生产环境使用
    // header('Access-Control-Allow-Origin: http://localhost:8081');

    // 允许的请求方法
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

    // 允许的请求头
    header('Access-Control-Allow-Headers: Content-Type, Authorization');

    // 如果是预检请求(OPTIONS)，直接返回200
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        http_response_code(200);
        exit();
    }

    header('Content-Type: application/json');
    http_response_code(200);
    print_r(json_encode([
        'msg' =>  '',
        'code' => 1,
        'data' => $res,
        'token' => md5('kodyToken')
    ]));
} catch (Exception $e) {
    $message = $e->getMessage();
    myResponse($message, 0, 200);
}

